<template>
  <div>
    <h2>审核题目</h2>
    <el-row
      :wrap="false"
      align="middle"
      gutter="12"
      justify="space-between"
      style="margin-bottom: 12px"
    >
      <el-col :span="6">
        <el-select
          v-model="selectedSubject"
          clearable
          placeholder="请选择科目"
          style="width: 100%"
          @change="loadPendingQuestions(1)"
        >
          <el-option v-for="subj in AllSubjects" :key="subj" :label="subj" :value="subj" />
        </el-select>
      </el-col>

      <el-col :span="6" style="text-align: right">
        <el-button
          :disabled="selectedIds.length === 0 || loading"
          style="margin-right: 8px"
          type="success"
          @click="batchApprove"
        >
          批量通过
        </el-button>
        <el-button
          :disabled="selectedIds.length === 0 || loading"
          type="danger"
          @click="batchReject"
        >
          批量拒绝
        </el-button>
      </el-col>
    </el-row>

    <el-row align="middle" justify="start" style="margin-bottom: 20px">
      <el-col :span="6">
        <el-input
          v-model="keyword"
          clearable
          placeholder="请输入关键词搜索"
          @clear="loadPendingQuestions(1)"
          @keyup.enter="loadPendingQuestions(1)"
        />
      </el-col>
    </el-row>

    <el-table
      :data="questions"
      :default-expand-all="false"
      :loading="loading"
      border
      row-key="questionId"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" prop="questionId" width="80" />
      <el-table-column label="题目内容">
        <template #default="{ row }">
          <div v-html="renderMarkdown(row.content)"></div>
        </template>
      </el-table-column>
      <el-table-column label="难度" prop="difficulty" width="100" />
      <el-table-column label="操作" width="260">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="viewDetail(row)">查看详情</el-button>
          <el-button size="small" type="success" @click="approve(row.questionId)">通过</el-button>
          <el-button size="small" type="danger" @click="reject(row.questionId)">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :page-size="PAGE_SIZE"
      :total="total"
      background
      layout="prev, pager, next"
      style="margin-top: 20px; text-align: right"
      @current-change="loadPendingQuestions"
    />

    <el-dialog
      v-model="detailDialogVisible"
      :before-close="closeDetailDialog"
      :title="'题目详情 - ID: ' + (detailQuestion?.questionId || '')"
      width="600px"
    >
      <div v-if="detailQuestion">
        <p><strong>题目内容：</strong></p>
        <div v-html="renderMarkdown(detailQuestion.content)"></div>

        <p><strong>题目类型：</strong> {{ typeMap[detailQuestion.type] || detailQuestion.type }}</p>
        <p><strong>难度：</strong> {{ detailQuestion.difficulty }}</p>
        <p><strong>创建时间：</strong> {{ formattedCreatedAt }}</p>

        <p><strong>选项：</strong></p>
        <ul v-if="detailOptions && detailOptions.length">
          <li v-for="(opt, index) in detailOptions" :key="index" v-html="renderMarkdown(opt)"></li>
        </ul>
        <pre v-else>{{ detailQuestion.options }}</pre>

        <p><strong>答案：</strong></p>
        <ul v-if="detailAnswer && detailAnswer.length">
          <li v-for="(ans, index) in detailAnswer" :key="index" v-html="renderMarkdown(ans)"></li>
        </ul>
        <pre v-else>{{ detailQuestion.answer }}</pre>

        <p><strong>解析：</strong></p>
        <div v-html="renderMarkdown(detailQuestion.analysis)"></div>
      </div>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { apiClient, handleErrorAndRedirect } from '@/api'
import { ElMessage } from 'element-plus'
import { AllSubjects, renderMarkdown } from '@/api/utils.ts'

const PAGE_SIZE = 10
const selectedSubject = ref<string | null>(null)
const questions = ref([])
const page = ref(1)
const total = ref(0)
const loading = ref(false)
const keyword = ref('')

const selectedIds = ref<number[]>([])

const detailDialogVisible = ref(false)
const detailQuestion = ref<any>(null)

const typeMap: Record<string, string> = {
  SINGLE_CHOICE: '单选题',
  MULTIPLE_CHOICE: '多选题',
  FILL_IN_BLANK: '填空题',
  SUBJECTIVE: '主观题',
}

const detailOptions = computed(() => {
  if (!detailQuestion.value?.options) return []
  try {
    const opts = JSON.parse(detailQuestion.value.options)
    if (Array.isArray(opts)) return opts
    if (typeof opts === 'object' && opts !== null) return Object.values(opts)
    return []
  } catch {
    return []
  }
})

const detailAnswer = computed(() => {
  if (!detailQuestion.value?.answer) return []
  try {
    const ans = JSON.parse(detailQuestion.value.answer)
    if (Array.isArray(ans)) return ans
    if (typeof ans === 'object' && ans !== null) return Object.values(ans)
    return []
  } catch {
    return []
  }
})

const formattedCreatedAt = computed(() => {
  if (!detailQuestion.value?.createdAt) return ''
  return new Date(detailQuestion.value.createdAt).toLocaleString()
})

async function loadPendingQuestions(p: number) {
  page.value = p
  loading.value = true
  try {
    const params: Record<string, any> = {
      keyword: keyword.value || undefined,
      subject: selectedSubject.value || undefined,
      pageSize: PAGE_SIZE,
    }
    const response = await apiClient.get('/admin/pending-questions/' + p, { params })
    questions.value = response.data.data
    total.value = response.data.total
    selectedIds.value = []
  } catch (error) {
    handleErrorAndRedirect(error, '加载待审核题目失败')
  } finally {
    loading.value = false
  }
}

function handleSelectionChange(selection: any[]) {
  selectedIds.value = selection.map((item) => item.questionId)
}

async function approve(id: number) {
  loading.value = true
  try {
    await apiClient.put(`/admin/questions/${id}/approve`)
    ElMessage.success('审批通过成功')
    await loadPendingQuestions(page.value)
  } catch (error) {
    ElMessage.error('审批失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

async function reject(id: number) {
  loading.value = true
  try {
    await apiClient.put(`/admin/questions/${id}/reject`)
    ElMessage.success('拒绝成功')
    await loadPendingQuestions(page.value)
  } catch (error) {
    ElMessage.error('拒绝失败，请稍后重试')
    console.error('拒绝失败', error)
  } finally {
    loading.value = false
  }
}

async function batchApprove() {
  if (selectedIds.value.length === 0) return
  loading.value = true
  try {
    await Promise.all(
      selectedIds.value.map((id) => apiClient.put(`/admin/questions/${id}/approve`)),
    )
    ElMessage.success('批量审批通过成功')
    await loadPendingQuestions(page.value)
  } catch (error) {
    ElMessage.error('批量审批失败，请稍后重试')
    console.error('批量审批失败', error)
  } finally {
    loading.value = false
  }
}

async function batchReject() {
  if (selectedIds.value.length === 0) return
  loading.value = true
  try {
    await Promise.all(selectedIds.value.map((id) => apiClient.put(`/admin/questions/${id}/reject`)))
    ElMessage.success('批量拒绝成功')
    await loadPendingQuestions(page.value)
  } catch (error) {
    ElMessage.error('批量拒绝失败，请稍后重试')
    console.error('批量拒绝失败', error)
  } finally {
    loading.value = false
  }
}

function viewDetail(row: any) {
  console.log('查看详情行:', row)
  detailQuestion.value = row
  detailDialogVisible.value = true
}

function closeDetailDialog() {
  detailDialogVisible.value = false
  detailQuestion.value = null
}

onMounted(() => {
  loadPendingQuestions(page.value)
})
</script>

<style scoped>
h2 {
  margin-bottom: 20px;
}
</style>
